module(..., package.seeall)
require "misc"
require "http"
require "log"
require "common"

require "PRO_style"
require "PRO_service_update"

ProjectSwitchBox = false
local width
local height
local cont

local page

local lock=false


local projectTab=nil


local function cbFnc(result,prompt,head,body)
    log.info("testHttp.cbFnc",result,prompt)
    if result and body then
        print(body)
        local tjsondata, r, errinfo = json.decode(body)
        log.info("解析结果：", r)
        if r then
            projectTab=tjsondata
        else
            print("json.decode error", errinfo)
        end
    end
end


local function res(r)
    if r then 
            lvgl.label_set_text(statusLabel, "#FFFFFF 升级文件下载成功,正在重启")
            lvgl.obj_align(statusLabel, bar, lvgl.ALIGN_OUT_TOP_MID, 0, -10)
        sys.timerStart(sys.restart,2000,"升级成功软件重启")
    end
end

local function updataFnc(code,status)
    log.info("update",code,status)
    if code ==1 then
        lvgl.label_set_text(statusLabel, "#FFFFFF "..status)
        lvgl.bar_set_value(bar,100, lvgl.ANIM_OFF)
        lock=false
    elseif code ==0 then 
        local lastIndex=status
        local lastLabelText=string.format("#FFFFFF 升级文件下载中 %d",status).."%"
        lvgl.bar_set_value(bar,lastIndex, lvgl.ANIM_ON)
        lvgl.label_set_text(statusLabel, lastLabelText)
        lvgl.obj_align(statusLabel, bar, lvgl.ALIGN_OUT_TOP_MID, 0, -10)
    end
end

local m_update = function(firmware_name)


    lock=true
    -- lvgl.page_clean(page)
    lvgl.obj_del(page)

    bar = lvgl.bar_create(cont, nil)
    lvgl.obj_set_size(bar, width/2, 15)
    lvgl.obj_align(bar,nil, lvgl.ALIGN_CENTET, 0, 0)
    lvgl.bar_set_value(bar, lastIndex, lvgl.ANIM_OFF)

    statusLabel=lvgl.label_create(cont, nil)
    lvgl.label_set_recolor(statusLabel, true)   
    lvgl.label_set_text(statusLabel, "#FFFFFF 正在请求升级")                  
    lvgl.label_set_text(statusLabel,lastLabelText)
    lvgl.obj_align(statusLabel, bar, lvgl.ALIGN_OUT_TOP_MID, 0, -10)

    local coreVer = rtos.get_version()
    local coreVersion = tonumber(coreVer:match(".-_V(%d+)"))
    -- local m_imei=misc.getImei()
    local m_imei="00000"..os.time()
    local url="###http://iot.openluat.com/api/site/firmware_upgrade?project_key=" .._G.PRODUCT_KEY .. "&imei="..m_imei .."&firmware_name="..firmware_name.."&core_version="..coreVersion.."&dfota=1&version=0.0.0"
    PRO_service_update.request(res,url,nil,nil,updataFnc)


end

local init = function()


    width = lvgl.obj_get_width(lvgl.scr_act())
    height = lvgl.obj_get_height(lvgl.scr_act())

    cont=lvgl.page_create(lvgl.scr_act(), nil)
    lvgl.obj_add_style(cont, lvgl.CONT_PART_MAIN, PRO_style.style_body)
    lvgl.obj_set_size(cont, width, height)
    lvgl.obj_align(cont, nil, lvgl.ALIGN_CENTER, 0, 0)

    page = lvgl.page_create(cont, nil)
    lvgl.obj_add_style(page, lvgl.CONT_PART_MAIN, PRO_style.style_temp)
    lvgl.obj_set_size(page, width*0.9, height/1.5)
    lvgl.obj_set_auto_realign(page, true)
    lvgl.obj_align(page, nil, lvgl.ALIGN_CENTER, 0, 0)
    -- lvgl.cont_set_fit(cont, lvgl.FIT_TIGHT)
    lvgl.page_set_scrl_layout(page,lvgl.LAYOUT_COLUMN_MID)

    -- 按键回调函数
    local event_handler = function(obj, event)
        if event == lvgl.EVENT_CLICKED then
            for _, v in pairs(projectTab) do
                if lvgl.obj_get_id(obj)==lvgl.obj_get_id(v.btn) then
                    m_update(v.firmware_name)
                    return
                end
            end
            -- m_update()
        end
    end

    local makeItem=function(mcont,t)

        local btn1 = lvgl.btn_create(mcont, nil)
        lvgl.obj_add_style(btn1, lvgl.CONT_PART_MAIN, PRO_style.style_btn)
        lvgl.obj_set_width(btn1,width /4)
        lvgl.obj_set_event_cb(btn1, event_handler)
        -- 按键1 的文字
        local label = lvgl.label_create(btn1, nil)
        lvgl.label_set_recolor(label, true)
        lvgl.label_set_text(label, "#FFFFFF "..t.name)
        t.btn=btn1
    end

    if projectTab then
        for _, v in pairs(projectTab) do
            makeItem(page,v)
            print(v)
        end
    else
        local label = lvgl.label_create(cont, nil)
        lvgl.label_set_recolor(label, true)
        lvgl.label_set_text(label, "#FFFFFF 正在导入升级文件...")
        lvgl.obj_align(label, nil, lvgl.ALIGN_CENTER, 0, 0)
    
    end
    
    ProjectSwitchBox = true

end

local uninit = function()
    if lock then return end
    lvgl.obj_del(cont)

    ProjectSwitchBox = false
end

local t
function keyMsg(msg)
    if msg.key_matrix_row .. msg.key_matrix_col == "00" then
        if msg.pressed then
            if ProjectSwitchBox then
                uninit()
                return
            end
            t = sys.timerStart(function()
                print("长按")
                init()
            end, 1000)
        else
            print("放开")
            if sys.timerIsActive(t) then sys.timerStop(t) end
        end
    end
end

sys.subscribe("projectSwitchInit", init)
sys.subscribe("projectSwitchUnInit", uninit)

sys.taskInit(function()
    http.request("GET","http://tools.openluat.com/api/site/dfoata_test_file",nil,nil,nil,nil,cbFnc)
    -- rtos.on(rtos.MSG_KEYPAD, keyMsg)
    -- rtos.init_module(rtos.MOD_KEYPAD, 0, 0xff, 0xff)
end)
